package com.edu.test;

import com.edu.bean.Student;
import com.edu.bean.User;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author:mx
 * @Date:2025/11/4-11:27:52
 */
public class MyTest5 {

    /*
    *       在Class对象中，使用 Constructor 这种类型的对象 来表示 一个构造方法的信息
    *           怎么获取构造方法
    *               getConstructors 获取所有的 公有的构造方法
    *               getDeclaredConstructors 获取所有的 公有/私有的构造方法
    *                getConstructor(Class...) 获取指定参数类型的公有构造方法
    *               getDeclaredConstructor(Class..)  获取指定参数类型的公有/私有 构造方法
    */
    @Test
    public void test01() throws NoSuchMethodException {
        Class clazz = User.class;
//        Constructor[] cons = clazz.getConstructors();
//        System.out.println(cons.length);
//        for (Constructor con : cons) {
//            System.out.println(con.getName());
//        }

        Constructor[] cons = clazz.getDeclaredConstructors();
        System.out.println(cons.length);
        for (Constructor con : cons) {
            System.out.println(con.getName());
        }

        Constructor constructor = clazz.getConstructor(int.class,String.class,String.class);
        Constructor cons2 = clazz.getDeclaredConstructor(int.class);
    }


    @Test
    public void test02() throws NoSuchMethodException {
        Class clazz = User.class;

        Constructor[] cons = clazz.getDeclaredConstructors();
        System.out.println(cons.length);
        for (Constructor con : cons) {
            System.out.println(con.getName());//
            System.out.println(con.getModifiers());
            System.out.println(con.getParameterCount());
            System.out.println("------------");
        }

        Constructor constructor = clazz.getConstructor(int.class,String.class,String.class);
        Constructor cons2 = clazz.getDeclaredConstructor(int.class);
    }


    @Test
    public void test03() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class clazz = User.class;

        Constructor constructor = clazz.getConstructor(int.class,String.class,String.class);

        Object o = constructor.newInstance(1, "zhangsan", "shufen");
        System.out.println(o);


        Constructor cons2 = clazz.getDeclaredConstructor(int.class);
        cons2.setAccessible(true);
        Object o1 = cons2.newInstance(5);
        System.out.println(o1);
    }

}
